package com.sgb.kjwl.view.widget.pick;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.LayoutBidderInformationBinding;
import com.sgb.kjwl.model.entity.InformationEntity;
import com.sgb.kjwl.model.entity.pick.EnterpriseBiddingDetailEntity5;
import com.sgb.kjwl.model.entity.pick.EnterpriseBiddingJoinEntity5;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.util.UiUtil;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.CustomFieldViewAdapter;
import com.sgb.kjwl.viewmodel.pick.EnterpriseBiddingModel5;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 招标报名的用户信息ui布局
 */
public class PickBidderInformationView extends LinearLayout implements ItemInputTextView.OnWholeItemClickListener {
    public InformationEntity etContacts;
    private Context mContext;
    private LayoutBidderInformationBinding binding;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;
    private boolean isLoadedUnit = false;
    //一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    //二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    //三级联动数据
    private List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;//城市一级位置标记
    private int cityPosition2;//城市二级位置标记
    private int cityPosition3;//城市三级位置标记
    private ImageAdapter imageAdapterImage; //图片
    private CustomFieldViewAdapter customFieldViewAdapter; //自定义字段
    private boolean isShowCityName = false; // 是否是回显省市区
    private EnterpriseBiddingModel5 model5;
    private EnterpriseBiddingDetailEntity5 detailData;
    private int type;
    private int verticalTypeValue;
    private Thread thread;
    private EnterpriseBiddingJoinEntity5 enterpriseBiddingJoinEntity5;

    /**
     * 用来处理城市数据
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    if (isShowCityName) {
                        if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getCity())) {
                            getCityName(detailData.getZcTenderingApplyDTO().getArea(), detailData.getZcTenderingApplyDTO().getCity(), detailData.getZcTenderingApplyDTO().getProvince());
                        }
                    } else {
                        showCityPop();
                        isLoaded = true;
                        thread = null;
                    }
                    break;
            }
        }
    };

    public PickBidderInformationView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    private void init() {
        binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.layout_bidder_information, this, true);
        binding.storageLocation.setOnWholeItemClickListener(this);
        binding.addressInfo.setOnWholeItemClickListener(this);
        initView();
    }

    private void initView() {
        binding.etPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        //android:inputType="numberDecimal"     8194
        binding.etPrice.getContent_edt().setInputType(8194);

        binding.storageLocation.getContent_edt().setMaxLines(1);
        binding.storageLocation.getContent_edt().setSingleLine(true);
        binding.storageLocation.getContent_edt().setEllipsize(TextUtils.TruncateAt.END);

        binding.addressInfo.getContent_edt().setMaxLines(1);
        binding.addressInfo.getContent_edt().setSingleLine(true);
        binding.addressInfo.getContent_edt().setEllipsize(TextUtils.TruncateAt.END);
//        binding.addressInfo.setPickRightImage(R.drawable.icon_landmark_location);

        EditText editText = binding.etPrice.getContent_edt();
        UiUtil.getInputFilter(editText,4);

        binding.etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String num = TextUtils.isEmpty(editable.toString()) ? "" : editable.toString();
                binding.tvNum.setText(num.length() + "/200");
            }
        });
        imageAdapterImage = new ImageAdapter(mContext, null, null, 1);
        binding.recyclerViewImage.setLayoutManager(new GridLayoutManager(mContext, 1));
        binding.recyclerViewImage.setAdapter(imageAdapterImage);

        customFieldViewAdapter = new CustomFieldViewAdapter(mContext, null);
        customFieldViewAdapter.setOnItemClick(new BaseRecycleAdapter.OnItemClick() {
            @Override
            public void onItemClick(Object o, int position) {
                setTestView();
            }
        });
        binding.addViewRv.setLayoutManager(new GridLayoutManager(mContext, 1));
        binding.addViewRv.setAdapter(customFieldViewAdapter);
        binding.ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (customFieldViewAdapter.getDatas().size() < 5) {
                    EnterpriseBiddingDetailEntity5.TenderingApplysEntity tenderingApplysEntity = new EnterpriseBiddingDetailEntity5.TenderingApplysEntity();
                    tenderingApplysEntity.setApplyContent("");
                    tenderingApplysEntity.setApplyTitle("");
                    customFieldViewAdapter.addData(tenderingApplysEntity);
                    customFieldViewAdapter.notifyDataSetChanged();
                }
                setTestView();
            }
        });
    }

    public void setinitView(int type, EnterpriseBiddingModel5 model5, int verticalTypeValue) {
        binding.setVariable(R.layout.layout_bidder_information, model5);
        this.model5 = model5;
        this.type = type;
        this.verticalTypeValue = verticalTypeValue;
        if (type == 1) {
            binding.llAddressView.setVisibility(View.GONE);
        } else {
            binding.llAddressView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 控制当前ui布局的显示和隐藏
     */
    public void setView(int type) {
        binding.rootLayout.setVisibility(type);
    }

    /**
     * 报名用户数据回显
     */
    public void initBidderInformation(EnterpriseBiddingDetailEntity5 detailData, EnterpriseBiddingJoinEntity5 enterpriseBiddingJoinEntity5) {
        this.detailData = detailData;
        this.enterpriseBiddingJoinEntity5 = enterpriseBiddingJoinEntity5;
        if (detailData != null) {
            if (detailData.getZcTenderingApplyDTO() != null) {
                if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getContacts())) {
                    binding.etContacts.setContent(detailData.getZcTenderingApplyDTO().getContacts());
                }
                if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getTel())) {
                    binding.etPhone.setContent(detailData.getZcTenderingApplyDTO().getTel());
                }
                if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getMoney())) {
                    binding.etPrice.setContent(detailData.getZcTenderingApplyDTO().getMoney());
                }
                if (type != 1) {
                    //  勘察设计”、“建筑设计”、“工程监理”、“工程造价咨询”、“工程总承包”      企业地址
                    //  当招标类型为“机械租赁”、“设备租赁”、“房产租赁”、“车辆租赁”           所在地
                    //  当招标类型为”劳务分包“、”专业工程“时，                            工队地址   其余为仓储地址
                    //  当招标类型为房产转让、机械转让、设备转让、车辆转让、其他：所在地址
                    //  当招标类型为土地产权转让：土地地址
                    //  当招标类型为物流货运：发货地址        PPP项目：项目地址

                    // 招标类型为 ”PPP项目“、”其他“ ，有  总报价(元)
                    // 招标类型为 ”土地产权转让、房产转让、物流货运、机械转让、设备转让、车辆转让“，无  总报价(元)


                    //竞价
                    // 3.3.1 企业地址：工程总包、PPP项目、土地产权转让、房产转让、设计规划、专业监理、地质勘察、造价咨询、机械转让、设备转让、车辆转让、物流货运、其他
                    //3.3.2 所在地：机械租赁、设备租赁、房产租赁、车辆租赁
                    if(type == 4){

                        if (detailData.getType() == 1 || detailData.getType() == 5 || detailData.getType() == 11 || detailData.getType() == 12) {
                            binding.storageLocation.setLabelName("所在地");
                        } else
                            binding.storageLocation.setLabelName("企业地址");
                        }

                    }else{
                        if (detailData.getType() == 6 || detailData.getType() == 7 || detailData.getType() == 8 || detailData.getType() == 9 || detailData.getType() == 10) {
                            binding.storageLocation.setLabelName("企业地址");
                        } else if (detailData.getType() == 1 || detailData.getType() == 5 || detailData.getType() == 11 || detailData.getType() == 12) {
                            binding.storageLocation.setLabelName("所在地");
                        } else if(detailData.getType() == 2 || detailData.getType() == 4){
                            binding.storageLocation.setLabelName("工队地址");
                        } else if(detailData.getType() == 14){
                            binding.storageLocation.setLabelName("土地地址");
                        } else if(detailData.getType() == 15 || detailData.getType() == 16 || detailData.getType() == 17 || detailData.getType() == 18|| detailData.getType() == 20){
                            binding.storageLocation.setLabelName("所在地址");
                        } else if(detailData.getType() == 19){
                            binding.storageLocation.setLabelName("发货地址");
                        } else if(detailData.getType() == 13){
                            binding.storageLocation.setLabelName("项目地址");
                        } else {
                            binding.storageLocation.setLabelName("仓储地址");
                        }
                    }

                    if(detailData.getType() == 6 || detailData.getType() == 7 || detailData.getType() == 8 || detailData.getType() == 9
                            || detailData.getType() == 10 || detailData.getType() == 13 || detailData.getType() == 20){
                        binding.etPrice.setVisibility(View.VISIBLE);
                    }else{
                        binding.etPrice.setVisibility(View.GONE);
                    }

                    if (0 != detailData.getZcTenderingApplyDTO().getLat()) {
                        enterpriseBiddingJoinEntity5.setLng(detailData.getZcTenderingApplyDTO().getLat() + "");
                    }
                    if (0 != detailData.getZcTenderingApplyDTO().getLng()) {
                        enterpriseBiddingJoinEntity5.setLng(detailData.getZcTenderingApplyDTO().getLng() + "");
                    }
                    if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getCity())) {
                        if (addressEntityList != null) {
                            isShowCityName = true;
                            getCityName(detailData.getZcTenderingApplyDTO().getArea(), detailData.getZcTenderingApplyDTO().getCity(), detailData.getZcTenderingApplyDTO().getProvince());
                        } else {
                            isShowCityName = true;
                            model5.getAddressModel(false);
                        }
                    }
                    if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getAddress())) {
                        enterpriseBiddingJoinEntity5.setAddress(detailData.getZcTenderingApplyDTO().getAddress());
                        binding.addressInfo.setContent(detailData.getZcTenderingApplyDTO().getAddress());
                    }

                }
                if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getRemark())) {
                    binding.etRemark.setText(detailData.getZcTenderingApplyDTO().getRemark());
                }
            }

            if (detailData.getTenderingApplys() != null && detailData.getTenderingApplys().size() != 0) {
                customFieldViewAdapter.addDatas(detailData.getTenderingApplys());
                customFieldViewAdapter.notifyDataSetChanged();
            }
        }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.storage_location:
                if (addressEntityList != null) {
                    isShowCityName = false;
                    showCityPop();
                } else {
                    isShowCityName = false;
                    model5.getAddressModel(true);
                }
                break;
            case R.id.address_info:
                if (!TextUtils.isEmpty(binding.storageLocation.getContent())) {
                    //跳转详细地址界面
                    model5.getLocationLL(model5.addMachineOutEntity.get().getProvinceNo(), model5.addMachineOutEntity.get().getCityNo(), model5.addMachineOutEntity.get().getAreaNo());
                } else {
                    MToast.showToast(mContext, "请选择所在地区");
                }
                break;
        }
    }

    private boolean setTestView() {
        int tag = 0;
        for (EnterpriseBiddingDetailEntity5.TenderingApplysEntity tenderingApplys1 : customFieldViewAdapter.getDatas()) {
            if (!TextUtils.isEmpty(tenderingApplys1.getApplyContent()) && !TextUtils.isEmpty(tenderingApplys1.getApplyTitle())) {
                tag++;
            }
        }
        if (tag == customFieldViewAdapter.getDatas().size() && customFieldViewAdapter.getDatas().size() < 5) {
            binding.ivAdd.setEnabled(true);
            binding.ivAdd.setImageResource(R.mipmap.add_ans);
            return true;
        } else {
            binding.ivAdd.setEnabled(false);
            binding.ivAdd.setImageResource(R.mipmap.add_ans_false);
            return false;
        }
    }

    //服务范围
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            if (isShowCityName) {
                if (!TextUtils.isEmpty(detailData.getZcTenderingApplyDTO().getCity())) {
                    if (addressEntityList != null) {
                        getCityName(detailData.getZcTenderingApplyDTO().getArea(), detailData.getZcTenderingApplyDTO().getCity(), detailData.getZcTenderingApplyDTO().getProvince());
                    }
                }
            } else {
                showCityPop();
            }
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        isShowCityName = false;
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(mContext, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                Objects.requireNonNull(model5.addMachineOutEntity.get()).setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                Objects.requireNonNull(model5.addMachineOutEntity.get()).setDistrict(opt3.get(options1).get(options2).get(options3).getName());

                enterpriseBiddingJoinEntity5.setAreacode(Integer.valueOf(opt3.get(options1).get(options2).get(options3).getNo()));
                enterpriseBiddingJoinEntity5.setArea(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.storageLocation.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setProvinceNo(addressEntityList.get(options1).getNo());
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setProvince(addressEntityList.get(options1).getName());
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setCity(opt2.get(options1).get(options2).getName());

            enterpriseBiddingJoinEntity5.setProvince(addressEntityList.get(options1).getNo());
            enterpriseBiddingJoinEntity5.setCity(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    public void getCityName(String areaCode, String cityCode, String provinceCode) {
        int options1 = 0, options2 = 0, options3 = 0;
        for (int k = 0; k < addressEntityList.size(); k++) { //省
            String provinceId = addressEntityList.get(k).getId();
            if (provinceCode.equals(provinceId)) {
                for (int j = 0; j < opt2.get(k).size(); j++) { //市
                    String cittId = opt2.get(k).get(j).getId();
                    if (cityCode.equals(cittId)) {
                        for (int i = 0; i < opt3.get(k).get(j).size(); i++) { // 区
                            String areaId = opt3.get(k).get(j).get(i).getId();
                            if (areaCode.equals(areaId)) {
                                options1 = k;
                                options2 = j;
                                options3 = i;
                                break;
                            }
                        }
                    }
                }
            }
        }
        String areaName;
        if (opt3.get(options1).get(options2).get(options3) == null) {
            areaName = "";
        } else {
            areaName = opt3.get(options1).get(options2).get(options3).getName();
            cityPosition3 = options3;
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
            Objects.requireNonNull(model5.addMachineOutEntity.get()).setDistrict(opt3.get(options1).get(options2).get(options3).getName());

            enterpriseBiddingJoinEntity5.setAreacode(Integer.valueOf(opt3.get(options1).get(options2).get(options3).getNo()));
            enterpriseBiddingJoinEntity5.setArea(opt3.get(options1).get(options2).get(options3).getName());
        }
        String content = addressEntityList.get(options1).getName()
                + opt2.get(options1).get(options2).getName()
                + areaName;
        binding.storageLocation.setContent(content);
        cityPosition1 = options1;
        cityPosition2 = options2;
        Objects.requireNonNull(model5.addMachineOutEntity.get()).setProvinceNo(addressEntityList.get(options1).getNo());
        Objects.requireNonNull(model5.addMachineOutEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
        Objects.requireNonNull(model5.addMachineOutEntity.get()).setProvince(addressEntityList.get(options1).getName());
        Objects.requireNonNull(model5.addMachineOutEntity.get()).setCity(opt2.get(options1).get(options2).getName());

        enterpriseBiddingJoinEntity5.setProvince(addressEntityList.get(options1).getName());
        enterpriseBiddingJoinEntity5.setCity(opt2.get(options1).get(options2).getName());
        isShowCityName = false;
    }


    /**
     * 解析城市数据
     */
    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /**
     * 更新用户选择的详细地址
     *
     * @param data
     */
    public void setAddressText(Intent data) {
        double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
        double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
        String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
        if (address.contains("省")) {
            String province[] = address.split("省");
            if (province.length > 1) {
                address = province[1];
            }
        }
        if (address.contains("市")) {
            String city[] = address.split("市");
            if (city.length > 1) {
                address = city[1];
            }
        }
        if (address.contains("区")) {
            String area[] = address.split("区");
            if (area.length > 1) {
                address = area[1];
            } else {
                address = area[0];
            }
        }
        binding.addressInfo.setContent(address + "");
        enterpriseBiddingJoinEntity5.setLat(lat + "");
        enterpriseBiddingJoinEntity5.setLng(lon + "");
        enterpriseBiddingJoinEntity5.setAddress(binding.addressInfo.getContent());
    }

    /**
     * 同步用户提交的图片
     *
     * @param urls
     */
    public void uploadImgSuccess(String urls) {
        List<String> url = new ArrayList<>();
        url.add(urls);
        imageAdapterImage.setNetImgList(url);
        imageAdapterImage.notifyDataSetChanged();
        binding.tvNumFile.setText("1/1");
    }

    /**
     * 获取输入框中用户输入的数据
     *
     * @return
     */
    public String getData() {
        if (TextUtils.isEmpty(binding.etContacts.getContent())) {
            return "请输入联系人";
        } else if (TextUtils.isEmpty(binding.etPhone.getContent())) {
            return "请输入联系电话";
        } else if (!CheckUtils.isMobileNum(binding.etPhone.getContent()) && !CheckUtils.IsTelephone(binding.etPhone.getContent())) {
            return "请填写正确的联系电话";
        }
        if (type != 1) {
            if (TextUtils.isEmpty(binding.storageLocation.getContent())) {
                return "请选择省市区";
            } else if (TextUtils.isEmpty(binding.addressInfo.getContent())) {
                return "请选择详细地址";
            } else if (TextUtils.isEmpty(binding.etPrice.getContent())) {
                if (verticalTypeValue != 3) {
                    if(detailData.getType() == 6 || detailData.getType() == 7 || detailData.getType() == 8 || detailData.getType() == 9
                            || detailData.getType() == 10 || detailData.getType() == 13 || detailData.getType() == 20){
                        return "请输入总报价";
                    }
                }
            }
        }
        if(detailData.getType() == 6 || detailData.getType() == 7 || detailData.getType() == 8 || detailData.getType() == 9
                || detailData.getType() == 10 || detailData.getType() == 13 || detailData.getType() == 20){
            enterpriseBiddingJoinEntity5.setMoney(binding.etPrice.getContent());
        }
        enterpriseBiddingJoinEntity5.setContacts(binding.etContacts.getContent());
        enterpriseBiddingJoinEntity5.setTel(binding.etPhone.getContent());
        String remark = TextUtils.isEmpty(binding.etRemark.getText()) ? "" : binding.etRemark.getText().toString();
        enterpriseBiddingJoinEntity5.setRemark(remark);
        if (!setTestView()) {
            return "新增标题与内容全部填写";
        }
        enterpriseBiddingJoinEntity5.setTenderingApplys(customFieldViewAdapter.getDatas());
        return "";
    }
}

